/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.ext.rs;

import java.io.InputStream;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.beaconframework.ext.rs.impl.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

public abstract class JsonToXmlQueryTemplate extends
        RestQueryTemplate<Document> {

    Logger log = LoggerFactory.getLogger(JsonToXmlQueryTemplate.class);
    String rootElementName = "root";


    public JsonToXmlQueryTemplate() {
        super();
        setAcceptedMediaTypes(new MediaType("application", "json"));
        setResponseEntityType(InputStream.class);
    }


    @Override
    public Document doTransform(Object input) throws Exception {

        JsonUtil ju = new JsonUtil();
        return ju.convert((InputStream) input);

    }


    @Override
    public Document doHandleException(Exception t) throws Exception {
        log.info("handling {} in {}.handleException", t, getClass());
        if (t instanceof WebApplicationException) {
            WebApplicationException wae = (WebApplicationException) t;
            Response r = wae.getResponse();

            log.info("Response code was: " + r.getStatus());
            if (r.getStatus() == 404) {
                Document d = org.beaconframework.util.xml.DomUtil
                        .newDocumentNamespaceAware();
                d.appendChild(d.createElement(getRootElementName()));
                return d;
            }
        }

        throw t;

    }


    public String getRootElementName() {
        return rootElementName;
    }


    public void setRootElementName(String rootElementName) {
        this.rootElementName = rootElementName;
    }

}
